package context

import (
	"context"
	"github.com/Unixeno/TheMoon/model"
	"github.com/Unixeno/TheMoon/moon/starlink"
	"sync"
)

type messageContext struct {
	ctx             context.Context
	cancel          context.CancelFunc
	client          starlink.Client
	channels        sync.Map // 模块对应的接收channel
	syncMessageChan sync.Map // map[message id] chan model.Message，收发同步消息时的映射表
}

func (ctx *messageContext) getChan(name string) chan model.Message {
	if channel, _ := ctx.channels.Load(name); channel != nil {
		return channel.(chan model.Message)
	}
	return nil
}

func (ctx *messageContext) registerModule(name string) {
	ctx.channels.Store(name, make(chan model.Message, 1))
}

func (ctx *messageContext) registerSyncChan(id string) <-chan model.Message {
	ch := make(chan model.Message)
	ctx.syncMessageChan.Store(id, ch)
	return ch
}

func (ctx *messageContext) unregisterSyncChan(id string) {
	ctx.syncMessageChan.Delete(id)
}

func (ctx *messageContext) getSyncChan(id string) chan<- model.Message {
	ch, ok := ctx.syncMessageChan.Load(id)
	if ok {
		return ch.(chan model.Message)
	}
	return nil
}
